<?php

namespace app\admin\controller\building\room\board;

use app\common\controller\Backend;
use app\admin\model\building\Room;
use app\admin\model\RoomBoardLogModel;
use app\admin\model\BillModel;
use app\admin\model\BuildingRoomBoardModel;
use app\common\model\PaymentRecords;
use think\Db;

/**
 * 楼栋房间仪表记录
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{

    /**
     * Log模型对象
     * @var \app\admin\model\building\room\board\Log
     */
    protected $model = null;
    protected $dataLimitField = 'user_id';
    protected $dataLimit = true;
    protected $dataLimitFieldAutoFill = true;
    
    protected $board_list = [
        1 => '水表',
        2 => '电表',
        3 => '燃气',
        4 => '热水'
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\building\room\board\Log;
        $this->view->assign("typeList", $this->model->getTypeList());

    }


/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
            
        foreach ($list as &$item) {
            if($room = Room::find($item['room_id'])){
                $item['room_name'] = $room->name;
            }else{
                $item['room_name'] = '';
            }
            
        }    
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    
    public function add()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        
        $data = $this->request->param('row/a');
        
        $room_id = $data['room_id'] ?? 0;
        $type = $data['type'] ?? 0;
        $num = $data['num'] ?? 0;
        $month = $data['month'] ?? date('Y-m', time());

        if ($num < 0) {
            $this->error('num错误');
        }

        $last_board = RoomBoardLogModel::where([
            'room_id' => $room_id,
            'type' => $type
        ])
            ->order('id desc')
            ->find();


        $last_num = $last_board->num ?? 0;

        if ($num < $last_num) {
            $this->error('最新值不能小于上期');
        }

        Db::startTrans();
        try {
            $price = BuildingRoomBoardModel::where([
                'room_id' => $room_id,
                'type' => $type
            ])->value('price', 0);

            $use_num = $num - $last_num;
            $money = bcmul($use_num, $price, 2);
            $log = RoomBoardLogModel::create([
                'user_id' => $this->auth->id,
                'room_id' => $room_id,
                'type' => $type,
                'name' => $this->board_list[$type],
                'num' => $num,
                'last_num' => $last_num,
                'use_num' => $use_num,
                'price' => $price,
                'money' => $money,
                'month' => date('Y-m', time()),
            ]);

            BuildingRoomBoardModel::update(['last_num' => $last_num], [
                'room_id' => $room_id,
                'type' => $type
            ]);

            $contract = \app\common\model\Contract::where('room_id', $room_id)
                ->order('id', 'desc')->find();

            if ($contract) {
                // 房东端账单
                $fee_arr = [
                    1 => '水费',
                    2 => '电费',
                    3 => '燃气费'
                ];
                $start_date = $contract->start_time;
                if ($last_board) {
                    $start_date = date('Y-m-d', $last_board->create_time);
                }
                $period = $start_date . '至' . date('Y-m-d');
                $category = $fee_arr[$type] ?? '未知';
                $bill = BillModel::create([
                    'user_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'status' => 0,
                    'money' => $money,
                    'year' => date('Y'),
                    'month' => date('Y-m'),
                    'day' => date('Y-m-d'),
                    'category' => $category,
                    'type' => $type + 2,//转换一下
                    'remark' => $category,
                    'period' => $period,
                ], true);


                // 用户端缴费
                $insert_data = [
                    'homeowner_id' => $contract->homeowner_id,
                    'contract_id' => $contract->id,
                    'relation_id' => $bill->id,
                    'user_id' => $contract->user_id,
                    'type' => PaymentRecords::TYPE_OTHER,
                    //'water_photo' => '',
                    //'electricity_photo' => '',
                    'status' => PaymentRecords::STATUS_DEFAULT,
                    'money' => $money,
                ];

                if ($type == 1) {
                    $insert_data['water_num'] = $num;
                    $insert_data['last_water_num'] = $last_num;
                    $insert_data['money_water'] = $money;
                } elseif ($type == 2) {
                    $insert_data['electricity_num'] = $num;
                    $insert_data['last_electricity_num'] = $last_num;
                    $insert_data['money_electricity'] = $money;
                } else {
                    $insert_data['other_fee'] = $money;
                    $other_data = [
                        [
                            'name' => '燃气费',
                            'money' => $money,
                        ]
                    ];
                    $insert_data['other_data'] = json_encode($other_data, JSON_UNESCAPED_UNICODE);
                }


                PaymentRecords::create($insert_data, true);
            }


            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('ok');
        
    }
    


}
